<template>
  <div class="settings">
    <el-card class="settings-card">
      <template #header>
        <div class="card-header">
          <span>系统设置</span>
          <el-button type="primary" @click="handleSave" :loading="saving">
            保存设置
          </el-button>
        </div>
      </template>

      <div v-loading="loading">
        <el-tabs v-model="activeTab">
          <!-- 基本设置 -->
          <el-tab-pane label="基本设置" name="basic">
            <el-form
              ref="basicFormRef"
              :model="basicForm"
              :rules="basicRules"
              label-width="120px"
            >
              <el-form-item label="网站名称" prop="siteName">
                <el-input v-model="basicForm.siteName" placeholder="请输入网站名称" />
              </el-form-item>
              <el-form-item label="网站Logo">
                <el-upload
                  class="logo-uploader"
                  :action="uploadUrl"
                  :show-file-list="false"
                  :on-success="handleLogoSuccess"
                  :before-upload="beforeLogoUpload"
                >
                  <img v-if="basicForm.logo" :src="basicForm.logo" class="logo" />
                  <el-icon v-else class="logo-uploader-icon"><Plus /></el-icon>
                </el-upload>
                <div class="upload-tip">建议尺寸：200x60px，支持jpg、png格式</div>
              </el-form-item>
              <el-form-item label="网站描述" prop="description">
                <el-input
                  v-model="basicForm.description"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入网站描述"
                />
              </el-form-item>
              <el-form-item label="联系电话" prop="contactPhone">
                <el-input v-model="basicForm.contactPhone" placeholder="请输入联系电话" />
              </el-form-item>
              <el-form-item label="联系邮箱" prop="contactEmail">
                <el-input v-model="basicForm.contactEmail" placeholder="请输入联系邮箱" />
              </el-form-item>
              <el-form-item label="备案信息" prop="icp">
                <el-input v-model="basicForm.icp" placeholder="请输入备案信息" />
              </el-form-item>
            </el-form>
          </el-tab-pane>

          <!-- 支付设置 -->
          <el-tab-pane label="支付设置" name="payment">
            <el-form
              ref="paymentFormRef"
              :model="paymentForm"
              :rules="paymentRules"
              label-width="120px"
            >
              <el-form-item label="支付宝支付">
                <el-switch v-model="paymentForm.alipayEnabled" />
              </el-form-item>
              <template v-if="paymentForm.alipayEnabled">
                <el-form-item label="AppID" prop="alipayAppId">
                  <el-input v-model="paymentForm.alipayAppId" placeholder="请输入支付宝AppID" />
                </el-form-item>
                <el-form-item label="商户私钥" prop="alipayPrivateKey">
                  <el-input
                    v-model="paymentForm.alipayPrivateKey"
                    type="textarea"
                    :rows="3"
                    placeholder="请输入商户私钥"
                  />
                </el-form-item>
                <el-form-item label="支付宝公钥" prop="alipayPublicKey">
                  <el-input
                    v-model="paymentForm.alipayPublicKey"
                    type="textarea"
                    :rows="3"
                    placeholder="请输入支付宝公钥"
                  />
                </el-form-item>
              </template>

              <el-form-item label="微信支付">
                <el-switch v-model="paymentForm.wechatEnabled" />
              </el-form-item>
              <template v-if="paymentForm.wechatEnabled">
                <el-form-item label="商户号" prop="wechatMchId">
                  <el-input v-model="paymentForm.wechatMchId" placeholder="请输入微信商户号" />
                </el-form-item>
                <el-form-item label="商户密钥" prop="wechatKey">
                  <el-input v-model="paymentForm.wechatKey" placeholder="请输入商户密钥" />
                </el-form-item>
                <el-form-item label="证书文件">
                  <el-upload
                    class="cert-uploader"
                    :action="uploadUrl"
                    :show-file-list="false"
                    :on-success="handleCertSuccess"
                    :before-upload="beforeCertUpload"
                  >
                    <el-button type="primary">上传证书</el-button>
                  </el-upload>
                  <div class="upload-tip">请上传微信支付证书文件</div>
                </el-form-item>
              </template>
            </el-form>
          </el-tab-pane>

          <!-- 物流设置 -->
          <el-tab-pane label="物流设置" name="logistics">
            <el-form
              ref="logisticsFormRef"
              :model="logisticsForm"
              :rules="logisticsRules"
              label-width="120px"
            >
              <el-form-item label="默认运费" prop="defaultFreight">
                <el-input-number
                  v-model="logisticsForm.defaultFreight"
                  :min="0"
                  :precision="2"
                  :step="1"
                />
              </el-form-item>
              <el-form-item label="满额包邮" prop="freeShippingAmount">
                <el-input-number
                  v-model="logisticsForm.freeShippingAmount"
                  :min="0"
                  :precision="2"
                  :step="10"
                />
              </el-form-item>
              <el-form-item label="物流公司">
                <el-checkbox-group v-model="logisticsForm.enabledCompanies">
                  <el-checkbox label="SF">顺丰速运</el-checkbox>
                  <el-checkbox label="ZTO">中通快递</el-checkbox>
                  <el-checkbox label="YTO">圆通速递</el-checkbox>
                  <el-checkbox label="YD">韵达快递</el-checkbox>
                  <el-checkbox label="STO">申通快递</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import service from '@/utils/request'

const loading = ref(false)
const saving = ref(false)
const activeTab = ref('basic')

// 表单引用
const basicFormRef = ref(null)
const paymentFormRef = ref(null)
const logisticsFormRef = ref(null)

// 上传地址
const uploadUrl = '/admin/upload'

// 基本设置表单
const basicForm = ref({
  siteName: '',
  logo: '',
  description: '',
  contactPhone: '',
  contactEmail: '',
  icp: ''
})

// 支付设置表单
const paymentForm = ref({
  alipayEnabled: false,
  alipayAppId: '',
  alipayPrivateKey: '',
  alipayPublicKey: '',
  wechatEnabled: false,
  wechatMchId: '',
  wechatKey: '',
  wechatCert: ''
})

// 物流设置表单
const logisticsForm = ref({
  defaultFreight: 0,
  freeShippingAmount: 0,
  enabledCompanies: []
})

// 表单验证规则
const basicRules = {
  siteName: [
    { required: true, message: '请输入网站名称', trigger: 'blur' }
  ],
  contactPhone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  contactEmail: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

const paymentRules = {
  alipayAppId: [
    { required: true, message: '请输入支付宝AppID', trigger: 'blur' }
  ],
  alipayPrivateKey: [
    { required: true, message: '请输入商户私钥', trigger: 'blur' }
  ],
  alipayPublicKey: [
    { required: true, message: '请输入支付宝公钥', trigger: 'blur' }
  ],
  wechatMchId: [
    { required: true, message: '请输入微信商户号', trigger: 'blur' }
  ],
  wechatKey: [
    { required: true, message: '请输入商户密钥', trigger: 'blur' }
  ]
}

const logisticsRules = {
  defaultFreight: [
    { required: true, message: '请输入默认运费', trigger: 'blur' }
  ],
  freeShippingAmount: [
    { required: true, message: '请输入满额包邮金额', trigger: 'blur' }
  ]
}

// 加载设置
const loadSettings = async () => {
  loading.value = true
  try {
    const res = await service.get('/admin/settings')
    const { basic, payment, logistics } = res.data
    
    basicForm.value = basic
    paymentForm.value = payment
    logisticsForm.value = logistics
  } catch (error) {
    console.error('加载设置失败：', error)
    ElMessage.error('加载设置失败')
  } finally {
    loading.value = false
  }
}

// Logo上传前的验证
const beforeLogoUpload = (file) => {
  const isImage = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('Logo只能是JPG或PNG格式！')
  }
  if (!isLt2M) {
    ElMessage.error('Logo大小不能超过2MB！')
  }

  return isImage && isLt2M
}

// Logo上传成功的回调
const handleLogoSuccess = (res) => {
  basicForm.value.logo = res.data.url
}

// 证书上传前的验证
const beforeCertUpload = (file) => {
  const isP12 = file.type === 'application/x-pkcs12'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isP12) {
    ElMessage.error('只能上传P12格式的证书文件！')
  }
  if (!isLt2M) {
    ElMessage.error('证书大小不能超过2MB！')
  }

  return isP12 && isLt2M
}

// 证书上传成功的回调
const handleCertSuccess = (res) => {
  paymentForm.value.wechatCert = res.data.url
}

// 保存设置
const handleSave = async () => {
  try {
    // 验证表单
    await Promise.all([
      basicFormRef.value?.validate(),
      paymentFormRef.value?.validate(),
      logisticsFormRef.value?.validate()
    ])
    
    saving.value = true
    await service.put('/admin/settings', {
      basic: basicForm.value,
      payment: paymentForm.value,
      logistics: logisticsForm.value
    })
    
    ElMessage.success('保存成功')
  } catch (error) {
    if (error === 'cancel') return
    console.error('保存失败：', error)
    ElMessage.error('保存失败，请重试')
  } finally {
    saving.value = false
  }
}

onMounted(() => {
  loadSettings()
})
</script>

<style lang="scss" scoped>
.settings {
  .settings-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }

  .logo-uploader {
    :deep(.el-upload) {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);

      &:hover {
        border-color: var(--el-color-primary);
      }
    }

    .logo-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 200px;
      height: 60px;
      text-align: center;
      line-height: 60px;
    }

    .logo {
      width: 200px;
      height: 60px;
      display: block;
    }
  }

  .cert-uploader {
    :deep(.el-upload) {
      display: block;
    }
  }

  .upload-tip {
    font-size: 12px;
    color: var(--el-text-color-secondary);
    margin-top: 8px;
  }
}
</style>
